package com.training.parser;

import com.training.bean.MvcBean;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Ywen on 2018/12/2.
 */
public class XMLParser {
    public static Map<String, MvcBean> load(String xmlPath) throws JDOMException, IOException {
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(new File(xmlPath));
        Element root = doc.getRootElement();
        Element actionMappings= root.getChild("actionMappings");
        List<Element> actionMappingRoot = actionMappings.getChildren();
        Map<String, MvcBean> mvcBeanMap = new HashMap<>();
        for (Element e : actionMappingRoot) {
            String name = e.getAttributeValue("name");

            Element formbeans = root.getChild("formbeans");
            List<Element> formBeanRoot = formbeans.getChildren();
            MvcBean bean = new MvcBean();
            for (Element formElement : formBeanRoot) {
                String beanName = formElement.getAttributeValue("name");
                if (name.equals(beanName)) {
                    bean.setName(beanName);
                    bean.setFormBeanType(formElement.getAttributeValue("type"));
                    break;
                }
            }

            bean.setActionType(e.getAttributeValue("type"));
            bean.setActionUrl(e.getAttributeValue("url"));
            List<Element> forward = e.getChildren();
            Map<String, String> forwardMap = new HashMap<>();
            for (Element element : forward) {
                forwardMap.put(element.getAttributeValue("name"), element.getAttributeValue("url"));
            }
            bean.setActionForwadMap(forwardMap);
            mvcBeanMap.put(e.getAttributeValue("url"), bean);
        }
        return mvcBeanMap;
    }

    public static void main(String[] args) throws JDOMException, IOException {
        load(System.getProperty("user.dir") + "/src/resources/config/mvc-config.xml");

    }
}
